
import React, { Component } from 'react'
import { Button, Input, Form, Select, message } from 'antd'
import { inject, observer } from 'mobx-react/index'
import request from '@/Utils/fecth'
import { address } from '@/Utils/apiConfig'

import './index.less'

const FormItem = Form.Item
const Option = Select.Option
const { peer: { creatPeer }, channelList, organization: { orgList, peerCheck }} = address.channelManagement

@inject('DataApprovalModel')
@observer

class CreateOrganization extends Component {
  constructor(props) {
    super(props)
    this.organizationId = this.props.location.state || ''
    this.state = {
      formArr: [
        {
          id1: 'name',
          id2: 'host',
          id3: 'username',
          id4: '_pwd',
          id5: 'description',
          id6: 'position',
          id7: 'remark',
          isCheck: 'false',
        },
      ],
      dataOptions: [],
      organizationId: this.organizationId,
      channelId: '',
      display: false,
      Display: false,
      channelOptions: [],
      loading: false,
      visible: false,
      type: '',
      currentValue: '',
      currentIndex: null,
      isChange: false,
      mode: this.props.DataApprovalModel.getConsortium().mode || '',
    }
  }
    // 添加节点
    addPeer = () => {
      const { formArr } = this.state
      const count = formArr.length
      const newData = {
        id1: `name${count}`,
        id2: `host${count}`,
        id3: `username${count}`,
        id4: `_pwd${count}`,
        id5: `description${count}`,
        id6: `position${count}`,
        id7: `remark${count}`,
        isCheck: 'false',
      }
      if (count <= 4) {
        formArr.push(newData)
        this.setState({
          formArr,
        })
      }
    }
    handleSubmit = (e) => {
      e.preventDefault()

      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (!this.state.organizationId) {
            return this.setState({ display: true })
          }
          if (!this.state.channelId) {
            return this.setState({ Display: true })
          }

          const { formArr } = this.state
          let resultChecking = formArr.filter(item => item.isCheck === 'checking').length
          let checkedResult = formArr.filter(item => item.isCheck === 'fail').length
          if (resultChecking) {
            return message.warning('节点正在检测中...请稍后再试')
          }
          if (checkedResult) { // 有错误的节点
            return message.warning('请检查节点参数')
          }
          this.setState({ loading: true })
          let obj = {
            ...values,
          }
          let arr = []
          for (let key in obj) {
            arr.push(obj[key])
          }
          let orgId = this.state.organizationId
          let channelId = this.state.channelId
          let options = {
            organizationId: orgId,
            channelId: channelId,
            peers: arr.map((ele, i, a) => {
              if (i % 7 === 0) {
                return {
                  name: a[i],
                  description: a[i + 1] || '',
                  host: a[i + 2],
                  username: a[i + 3],
                  _pwd: a[i + 4],
                  position: a[i + 5] || '',
                  remark: a[i + 6] || '',

                }
              }
              return null
            }).filter(ele => ele !== null),
            mode: this.props.DataApprovalModel.getConsortium().mode || '',
          }
          request().post(creatPeer, options, {
            headers: {
              'x-request-from': 'BaaS',
            },
          }).then((res) => {
            if (res && res.status === 200) {
              message.success('节点创建成功')
              this.props.history.push({
                pathname: '/dashboard/peerManagement',
              })
            } else {
              this.setState({ loading: false })
            }
          })
        }
      })
    }

    deletePeer = (index) => {
      const { formArr } = this.state
      formArr.splice(index, 1)
      this.setState({
        formArr,
      })
    }
    componentDidMount() {
      this.getData()
      let id = this.props.DataApprovalModel.getConsortium().id

      request().get(`${orgList.format({ id: id })}`, {
        headers: {
          'x-request-from': 'BaaS',
        },
      }).then((res) => {
        if (res && res.data && res.data.code === 200) {
          let dataOptions = res.data.data
          this.setState({
            dataOptions,
          })
        }
      })
    }
    getData = () => {
      let id = this.props.DataApprovalModel.getConsortium().id
      request().get(`${channelList.format({ id: id })}`, {
        headers: {
          'x-request-from': 'BaaS',
        },
      }).then(res => {
        if (res && res.status === 200) {
          this.setState({
            channelOptions: res.data.data,
          })
        }
      })
    }
    handleBack = () => {
      window.history.go(-1)
    }
    handleOk = (e) => {
      this.setState({
        visible: false,
      })
    }
    handleCancel = (e) => {
      this.setState({
        visible: false,
      })
    }
    focusInitValue = (e, i) => {
      this.setState({
        currentValue: e.target.value,
        currentIndex: i,
        isChange: false,
      })
    }
    changeValueCheck = (e, i, id) => {
      const { formArr } = this.state
      formArr[i].isCheck = 'false'
      formArr[i][id] = e.target && e.target.value
      this.setState({
        formArr,
        isChange: true,
      })
    }
    // 准备检测
    peerCheckStart = (arr, i, id) => {
      const { getFieldValue } = this.props.form
      const { formArr, currentIndex, currentValue, isChange } = this.state
      // 如果节点ip和用户名和密码都输入的话

      if (getFieldValue(arr[0]) && getFieldValue(arr[2]) && getFieldValue(arr[3])) {
        if (currentIndex === i && (formArr[i][id] ? formArr[i][id] === currentValue : false) && !isChange) {
          return
        } else {
          formArr[i].isCheck = 'checking'
          this.setState({
            formArr,
          })
          let check = {
            host: getFieldValue(arr[0]),
            username: getFieldValue(arr[2]),
            _pwd: getFieldValue(arr[3]),
            // description: getFieldValue(arr[1]) || "",
            // remark: getFieldValue(arr[5]) || "",
            // position: getFieldValue(arr[4]) || "",
          }
          request().post(peerCheck, check, {
            headers: {
              'x-request-from': 'BaaS',
            },
          }).then((res) => {
            if (res) {
              switch (res.status) {
              case 200:
                formArr[i].isCheck = 'true'
                this.setState({
                  formArr,
                })
                break

              default:
                formArr[i].isCheck = 'fail'
                this.setState({
                  formArr,
                })
                break
              }
            } else {
              formArr[i].isCheck = 'fail'
              this.setState({
                formArr,
              })
            }
          })
        }
      }
    }
    goBack = () => {
      this.props.history.goBack()
    }
    render() {
      const { getFieldDecorator, getFieldValue } = this.props.form
      const { dataOptions, channelOptions } = this.state
      return (
        <div className="create-peer common">
          <div className="breadcrumb-header">
            <img src={require('../../../../../../images/common/back.svg')} onClick={() => this.goBack()} />
            <div className="breadcrumb-back" onClick={() => this.goBack()}>
                        返回
            </div>
            <div className="breadcrumb-before" onClick={() => this.props.history.push({ pathname: '/dashboard/peerManagement' })}>节点管理</div>
            <div className="line">&nbsp;/&nbsp;</div>
            <div className="breadcrumb-current">新增节点</div>
          </div>
          <div className="wrapper">
            <div className="create-wrapper">
              <div className="organization-wrapper">
                <div className="wrapper-input">
                  <div className="organization-name">组织名称：</div>
                  <div>
                    {
                      this.organizationId
                        ? <p className="desc">{localStorage.getItem('orgName')}</p>
                        : <div id="selectBox">
                          <Select
                            showSearch
                            getPopupContainer={() => document.getElementById('selectBox')}
                            style={{ width: 312, height: 36 }}
                            placeholder={'请选择组织'}
                            optionFilterProp="children"
                            suffixIcon={
                              <div className="triangle"></div>
                            }
                            onSelect={(value) => this.setState({
                              organizationId: value,
                              display: false,
                            })}
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                          >
                            {
                              dataOptions.length > 0 && dataOptions.map((item, index) => {
                                return <Option value={item.id} key={item.id}>{item.name}</Option>
                              })
                            }
                          </Select>
                        </div>
                    }

                    <div style={{ display: this.state.display ? '' : 'none' }} className="error">请选择组织!</div>
                  </div>
                </div>
                <div className="wrapper-input">
                  <div className="organization-name">组织类型：</div>
                  <div className="desc">peer</div>
                </div>
                <div className="wrapper-input" style={{ alignItems: 'flex-start' }}>
                  <div className="organization-name" style={{ marginTop: 8 }}>配置节点</div>
                  <div>
                    <div className="form-wrapper">
                      <div className="title">
                        <div style={{ width: 89, marginRight: 12 }}>Peer节点</div>
                        <div style={{ width: 112, marginRight: 12 }}>节点描述</div>
                        <div style={{ width: 112, marginRight: 12 }}>节点IP</div>
                        <div style={{ width: 112, marginRight: 12 }}>SSH用户名</div>
                        <div style={{ width: 112, marginRight: 12 }}>SSH密码</div>
                        <div style={{ width: 112, marginRight: 12 }}>节点位置</div>
                        <div style={{ width: 112, marginRight: 12 }}>节点备注</div>
                        <div>检测结果</div>
                      </div>
                      {
                        this.state.formArr.length > 0 && this.state.formArr.map((item, index) => {
                          return (
                            <Form key={item.id1} className="form-user">
                              <div style={{ display: 'flex' }}>
                                <FormItem className="input-wrap" >
                                  {getFieldDecorator(item.id1, {
                                    rules: [{
                                      required: true,
                                      pattern: /^[^\u4e00-\u9fa5]+$/,
                                      message: '格式错误',
                                    }, {
                                      validator: this.handleAddress,
                                    }],
                                  })(
                                    <Input
                                      autoComplete="off"
                                      // placeholder='请输入名称'
                                      style={{ width: 89, marginRight: 12 }}
                                      onChange={(value) => {
                                        this.setState({ a: value })
                                      }} />
                                  )}
                                </FormItem>
                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id5, {
                                    // rules: [{
                                    //     required: true,
                                    //     message: "请输入描述",
                                    // }],
                                  })(
                                    <div>
                                      <Input
                                        // placeholder='请输入描述'
                                        autoComplete="off"
                                        style={{ width: 112, marginRight: 12 }}
                                        // onFocus={(e) => { this.focusInitValue(e, index) }}
                                        // onChange={(e) => { this.changeValueCheck(e, index, item.id5) }}
                                        // onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id5)}
                                      />
                                    </div>
                                  )}
                                </FormItem>
                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id2, {
                                    rules: [{
                                      required: true,
                                      pattern: /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/,
                                      message: '格式错误',
                                    }, {
                                      validator: this.handleIP,
                                    }],
                                  })(
                                    <div>
                                      <Input
                                        autoComplete="off"
                                        // placeholder='请输入IP'
                                        style={{ width: 112, marginRight: 12 }}
                                        onFocus={(e) => { this.focusInitValue(e, index) }}
                                        onChange={(e) => { this.changeValueCheck(e, index, item.id2) }} onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id2)} />
                                    </div>
                                  )}
                                </FormItem>

                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id3, {
                                    rules: [{
                                      required: true,
                                      message: '请输入用户名',
                                    }, {
                                      validator: this.handleAddress,
                                    }],
                                  })(
                                    <Input
                                      // placeholder='请输入用户名'
                                      autoComplete="off"
                                      style={{ width: 112, marginRight: 12 }}
                                      onFocus={(e) => { this.focusInitValue(e, index) }} onChange={(e) => { this.changeValueCheck(e, index, item.id3) }} onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id3)} />
                                  )}
                                </FormItem>
                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id4, {
                                    rules: [{
                                      required: true,
                                      message: '请输入密码',
                                    }, {
                                      validator: this.handleAddress,
                                    }],
                                  })(
                                    <Input
                                      autoComplete="off"
                                      type="_pwd"
                                      // placeholder='请输入密码'
                                      style={{ width: 112, marginRight: 12 }}
                                      onFocus={(e) => { this.focusInitValue(e, index) }} onChange={(e) => { this.changeValueCheck(e, index, item.id4) }} onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id4)} />
                                  )}
                                </FormItem>
                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id6,
                                    {
                                      // rules: [{
                                      //     required: true,
                                      //     message: "请输入位置",
                                      // }],
                                    })(
                                    <Input
                                      autoComplete="off"
                                      className="place-holder"
                                      // placeholder='以;分割经纬度'
                                      style={{ width: 112, marginRight: 12 }}
                                      // onFocus={(e) => { this.focusInitValue(e, index) }}
                                      // onChange={(e) => { this.changeValueCheck(e, index, item.id6) }}
                                      // onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id6)}
                                    />
                                  )}
                                </FormItem>
                                <FormItem className="input-wrap">
                                  {getFieldDecorator(item.id7, {
                                    // rules: [{
                                    //     required: true,
                                    //     message: "请输入备注",
                                    // }],
                                  })(
                                    <Input
                                      autoComplete="off"
                                      // placeholder='请输入备注'
                                      style={{ width: 112, marginRight: 12 }}
                                      // onFocus={(e) => { this.focusInitValue(e, index) }}
                                      // onChange={(e) => { this.changeValueCheck(e, index, item.id7) }}
                                      // onBlur={() => this.peerCheckStart([item.id2, item.id5, item.id3, item.id4, item.id6, item.id7], index, item.id7)}
                                    />
                                  )}
                                </FormItem>
                                <FormItem className="check-result">
                                  <span className={item.isCheck === 'false' ? (getFieldValue(item.id2) && getFieldValue(item.id3) && getFieldValue(item.id4) ? 'test-peer test-peer-init' : 'test-peer test-peer-default') : item.isCheck === 'fail' ? 'test-peer test-peer-error' : item.isCheck === 'true' ? 'test-peer test-peer-success' : item.isCheck === 'checking' ? 'test-peer test-peer-init' : ''}>{item.isCheck === 'false' ? '待检测' : item.isCheck === 'fail' ? '失败' : item.isCheck === 'true' ? '通过' : item.isCheck === 'checking' ? '检测中...' : ''}</span>
                                </FormItem>
                                <FormItem>
                                  {
                                    index !== 0 && <span className="close" onClick={() => this.deletePeer(index)}>×</span>
                                  }

                                </FormItem>
                              </div>
                            </Form>
                          )
                        })
                      }
                      <p className="icon-plus">
                        <img src={require('../../../../../../images/peer/add.svg')} style={{ cursor: 'pointer', marginRight: 7 }} onClick={this.addPeer} />
                        <span onClick={this.addPeer}>添加Peer节点</span>
                                            最多添加4个节点
                      </p>
                    </div>
                    <p className="peer-desc">节点由用户提供外网节点，需要在节点上安装docker并支持Https调用</p>
                  </div>
                </div>
                <div className="wrapper-input">
                  <div className="organization-name">通道选择：</div>
                  <div>
                    <div ref="selectBox">
                      <Select
                        showSearch
                        suffixIcon={
                          <div className="triangle"></div>
                        }
                        getPopupContainer={() => this.refs.selectBox}
                        style={{ width: 312, height: 36 }}
                        placeholder={'请选择通道'}
                        optionFilterProp="children"
                        onSelect={(value) => this.setState({
                          channelId: value,
                          Display: false,
                        })}
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                      >
                        {
                          channelOptions.length > 0 && channelOptions.map((item, index) => {
                            return <Option value={item._id} key={index}>{item.name}</Option>
                          })
                        }
                      </Select>
                    </div>
                    <span style={{ display: this.state.Display ? '' : 'none' }} className="error">请选择通道!</span>
                  </div>
                </div>
              </div>
              <div>
                <FormItem style={{ marginLeft: 78 }}>
                  <Button onClick={this.handleSubmit} loading={this.state.loading} type="primary">{'确定'}</Button>
                  <Button disabled={this.state.loading} onClick={this.handleBack}>取消</Button>
                </FormItem>
              </div>
            </div>
          </div>

        </div>
      )
    }
}
export default CreateOrganization = Form.create()(CreateOrganization)
